package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func GetDataB(c *gin.Context) {
	var b StructB
	c.Bind(&b)
	c.JSON(200, gin.H{
		"a": b.NestedStruct,
		"b": b.FieldB,
	})
}

func GetDataC(c *gin.Context) {
	var b StructC
	c.Bind(&b)
	c.JSON(200, gin.H{
		"a": b.NestedStructPointer,
		"c": b.FieldC,
	})
}

func GetDataD(c *gin.Context) {
	var b StructD
	c.Bind(&b)

	c.JSON(200, gin.H{
		"x": b.NestedAnonyStruct,
		"d": b.FieldD,
	})
}

func formHandler(c *gin.Context) {
	var fakeForm MyForm
	c.ShouldBind(&fakeForm)

	var queryStr string
	xx, ok := c.GetQuery("xx")
	yy, ok1 := c.GetQuery("yy")
	if ok && ok1 {
		queryStr = "xx=" + xx + "&&yy=" + yy
	}

	header1 := c.GetHeader("a")

	c.JSON(200, gin.H{
		"colors":   fakeForm.Colors,
		"queryStr": queryStr,
		"headers":  header1,
	})
}

func indexHandler(c *gin.Context) {
	c.HTML(200, "form.html", nil)
}

func startPage(c *gin.Context) {
	var person Person
	if c.ShouldBind(&person) == nil {
		c.String(200, "===== Bind By Query String =====\n")
		log.Println(person.Name)
		log.Println(person.Address)
		log.Println(person.Birthday)
	}

	if c.ShouldBindJSON(&person) == nil {
		c.String(200, "===== Bind By JSON =====\n")
		log.Println(person.Name)
		log.Println(person.Address)
	}

	c.String(200, "Success")
}

func main() {
	r := gin.Default()

	r.LoadHTMLGlob("views/*")

	r.GET("/ping", func(ctx *gin.Context) {
		ctx.JSON(200, gin.H{
			"message": "pong1",
		})
	})

	r.GET("/someJSON", func(ctx *gin.Context) {
		data := map[string]interface{}{
			"lang": "GO 语言",
			"tag":  "<br>",
		}
		ctx.AsciiJSON(http.StatusOK, data)
	})

	r.GET("/testing", startPage)

	r.GET("/getb", GetDataB)

	r.GET("getc", GetDataC)

	r.GET("getd", GetDataD)

	r.GET("/", indexHandler)

	r.POST("/", formHandler)

	r.GET("/:name/:id", func(ctx *gin.Context) {
		var person1 Person1
		if err := ctx.ShouldBindUri(&person1); err != nil {
			ctx.JSON(400, gin.H{
				"msg": err.Error(),
			})
			return
		}
		ctx.JSON(200, gin.H{
			"name": person1.Name,
			"id":   person1.ID,
		})
	})

	r.Run("localhost:8081")
}
